package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.mybatisPlus.BaseServiceImpl;
import com.ruoyi.system.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.SysRoleDept;
import com.ruoyi.system.domain.SysRoleMenu;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.service.ISysRoleService;

import javax.annotation.Resource;

/**
 * 角色 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysRoleServiceImpl extends BaseServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysRoleDeptMapper roleDeptMapper;

    @Resource
    private SysDeptMapper sysDeptMapper;

    /**
     * 根据条件分页查询角色数据
     *
     * @param role 角色信息
     * @return 角色数据集合信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysRole> selectRoleList(SysRole role) {
//        return roleMapper.selectRoleList(role);
        // 构建多表联查条件
        MPJLambdaWrapper<SysRole> wrapper = new MPJLambdaWrapper<SysRole>()
                .selectAll(SysRole.class)
                .distinct()
                .leftJoin(SysUserRole.class, SysUserRole::getRoleId, SysRole::getRoleId)
                .leftJoin(SysUser.class, SysUser::getUserId, SysUserRole::getUserId).disableSubLogicDel()
                .leftJoin(SysDept.class, "d",SysDept::getDeptId, SysUser::getDeptId).disableSubLogicDel()
                .eq(role.getRoleId() != null && role.getRoleId() != 0L, SysRole::getRoleId, role.getRoleId())
                .like(StringUtils.isNotBlank(role.getRoleName()), SysRole::getRoleName, role.getRoleName())
                .eq(StringUtils.isNotBlank(role.getStatus()), SysRole::getStatus, role.getStatus())
                .like(StringUtils.isNotBlank(role.getRoleKey()), SysRole::getRoleKey, role.getRoleKey())
                .ge(role.getParams() != null && ObjectUtil.isNotEmpty(role.getParams().get("beginTime")),
                        SysRole::getCreateTime, DateUtils.parseDate(role.getParams().get("beginTime")))
                .le(role.getParams() != null && ObjectUtil.isNotEmpty(role.getParams().get("endTime")),
                        SysRole::getCreateTime, DateUtils.parseDate(role.getParams().get("endTime")))
                .apply((role.getParams() != null && ObjectUtil.isNotEmpty(role.getParams().get("dataScope"))) , String.valueOf(role.getParams().get("dataScope")))
                .orderByAsc(SysRole::getRoleSort);

        // 执行查询并获取结果
        return roleMapper.selectJoinList(SysRole.class, wrapper);
    }

    /**
     * 根据用户ID查询角色
     *
     * @param userId 用户ID
     * @return 角色列表
     */
    @Override
    public List<SysRole> selectRolesByUserId(Long userId) {
//        List<SysRole> userRoles = roleMapper.selectRolePermissionByUserId(userId);
        MPJLambdaWrapper<SysRole> wrapper = new MPJLambdaWrapper<SysRole>()
                .selectAll(SysRole.class)
                .distinct()
                .leftJoin(SysUserRole.class, SysUserRole::getRoleId, SysRole::getRoleId)
                .leftJoin(SysUser.class, SysUser::getUserId, SysUserRole::getUserId).disableSubLogicDel()
                .leftJoin(SysDept.class, SysDept::getDeptId, SysUser::getDeptId).disableSubLogicDel()
                .eq(SysUserRole::getUserId, userId);
        List<SysRole> userRoles = roleMapper.selectJoinList(SysRole.class, wrapper);

        List<SysRole> roles = selectRoleAll();
        for (SysRole role : roles) {
            for (SysRole userRole : userRoles) {
                if (role.getRoleId().longValue() == userRole.getRoleId().longValue()) {
                    role.setFlag(true);
                    break;
                }
            }
        }
        return roles;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRolePermissionByUserId(Long userId) {
//        List<SysRole> perms = roleMapper.selectRolePermissionByUserId(userId);
        MPJLambdaWrapper<SysRole> wrapper = new MPJLambdaWrapper<SysRole>()
                .selectAll(SysRole.class)
                .distinct()
                .leftJoin(SysUserRole.class, SysUserRole::getRoleId, SysRole::getRoleId)
                .leftJoin(SysUser.class, SysUser::getUserId, SysUserRole::getUserId).disableSubLogicDel()
                .leftJoin(SysDept.class, SysDept::getDeptId, SysUser::getDeptId).disableSubLogicDel()
                .eq(SysUserRole::getUserId, userId);
        List<SysRole> perms = roleMapper.selectJoinList(SysRole.class, wrapper);
        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms) {
            if (StringUtils.isNotNull(perm)) {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 查询所有角色
     *
     * @return 角色列表
     */
    @Override
    public List<SysRole> selectRoleAll() {
        return SpringUtils.getAopProxy(this).selectRoleList(new SysRole());
    }

    /**
     * 根据用户ID获取角色选择框列表
     *
     * @param userId 用户ID
     * @return 选中角色ID列表
     */
    @Override
    public List<Long> selectRoleListByUserId(Long userId) {
//        return roleMapper.selectRoleListByUserId(userId);
        // 构建多表联查条件
        MPJLambdaWrapper<SysRole> wrapper = new MPJLambdaWrapper<SysRole>()
                .select(SysRole::getRoleId)
                .leftJoin(SysUserRole.class, SysUserRole::getRoleId, SysRole::getRoleId)
                .leftJoin(SysUser.class, SysUser::getUserId, SysUserRole::getUserId)
                .eq(SysUser::getUserId, userId);

        // 执行查询并获取结果
        List<SysRole> sysRoles = roleMapper.selectJoinList(SysRole.class, wrapper);
        return sysRoles.stream()
                .map(SysRole::getRoleId)
                .collect(Collectors.toList());
    }

    /**
     * 通过角色ID查询角色
     *
     * @param roleId 角色ID
     * @return 角色对象信息
     */
    @Override
    public SysRole selectRoleById(Long roleId) {
//        return roleMapper.selectRoleById(roleId);
        MPJLambdaWrapper<SysRole> wrapper = new MPJLambdaWrapper<SysRole>()
                .selectAll(SysRole.class)
                .distinct()
                .leftJoin(SysUserRole.class, SysUserRole::getRoleId, SysRole::getRoleId)
                .leftJoin(SysUser.class, SysUser::getUserId, SysUserRole::getUserId).disableSubLogicDel()
                .leftJoin(SysDept.class, SysDept::getDeptId, SysUser::getDeptId).disableSubLogicDel()
                .eq(SysRole::getRoleId, roleId);
        return roleMapper.selectJoinOne(SysRole.class, wrapper);
    }

    /**
     * 校验角色名称是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public boolean checkRoleNameUnique(SysRole role) {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
//        SysRole info = roleMapper.checkRoleNameUnique(role.getRoleName());

        MPJLambdaWrapper<SysRole> wrapper = new MPJLambdaWrapper<SysRole>()
                .selectAll(SysRole.class)
                .distinct()
                .leftJoin(SysUserRole.class, SysUserRole::getRoleId, SysRole::getRoleId)
                .leftJoin(SysUser.class, SysUser::getUserId, SysUserRole::getUserId).disableSubLogicDel()
                .leftJoin(SysDept.class, SysDept::getDeptId, SysUser::getDeptId).disableSubLogicDel()
                .eq(SysRole::getRoleName,role.getRoleName());
        // 执行查询并获取结果列表
        List<SysRole> result = roleMapper.selectJoinList(SysRole.class, wrapper);

        // 确保只返回一条记录
        SysRole info =  result.isEmpty() ? null : result.get(0);

        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色权限是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public boolean checkRoleKeyUnique(SysRole role) {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
//        SysRole info = roleMapper.checkRoleKeyUnique(role.getRoleKey());
        MPJLambdaWrapper<SysRole> wrapper = new MPJLambdaWrapper<SysRole>()
                .selectAll(SysRole.class)
                .distinct()
                .leftJoin(SysUserRole.class, SysUserRole::getRoleId, SysRole::getRoleId)
                .leftJoin(SysUser.class, SysUser::getUserId, SysUserRole::getUserId).disableSubLogicDel()
                .leftJoin(SysDept.class, SysDept::getDeptId, SysUser::getDeptId).disableSubLogicDel()
                .eq(SysRole::getRoleKey,role.getRoleKey());
        // 执行查询并获取结果列表
        List<SysRole> result = roleMapper.selectJoinList(SysRole.class, wrapper);

        // 确保只返回一条记录
        SysRole info =  result.isEmpty() ? null : result.get(0);
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色是否允许操作
     *
     * @param role 角色信息
     */
    @Override
    public void checkRoleAllowed(SysRole role) {
        if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员角色");
        }
    }

    /**
     * 校验角色是否有数据权限
     *
     * @param roleIds 角色id
     */
    @Override
    public void checkRoleDataScope(Long... roleIds) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            for (Long roleId : roleIds) {
                SysRole role = new SysRole();
                role.setRoleId(roleId);
                List<SysRole> roles = SpringUtils.getAopProxy(this).selectRoleList(role);
                if (StringUtils.isEmpty(roles)) {
                    throw new ServiceException("没有权限访问角色数据！");
                }
            }
        }
    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int countUserRoleByRoleId(Long roleId) {
//        return userRoleMapper.countUserRoleByRoleId(roleId);
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getRoleId, roleId);
        return userRoleMapper.selectCount(wrapper);
    }

    /**
     * 新增保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertRole(SysRole role) {
        // 新增角色信息
        roleMapper.insert(role);
        return insertRoleMenu(role);
    }

    /**
     * 修改保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateRole(SysRole role) {
        // 修改角色信息
        roleMapper.updateById(role);
        // 删除角色与菜单关联
//        roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<SysRoleMenu>();
        wrapper.eq(SysRoleMenu::getRoleId, role.getRoleId());
        roleMenuMapper.delete(wrapper);
        return insertRoleMenu(role);
    }

    /**
     * 修改角色状态
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public int updateRoleStatus(SysRole role) {
        return roleMapper.updateById(role);
    }

    /**
     * 修改数据权限信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int authDataScope(SysRole role) {
        // 修改角色信息
        roleMapper.updateById(role);
        // 删除角色与部门关联
//        roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId());
        LambdaQueryWrapper<SysRoleDept> wrapper = new LambdaQueryWrapper<SysRoleDept>();
        wrapper.eq(SysRoleDept::getRoleId, role.getRoleId());
        roleDeptMapper.delete(wrapper);
        // 新增角色和部门信息（数据权限）
        return insertRoleDept(role);
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    public int insertRoleMenu(SysRole role) {
        int rows = 1;
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<>();
        for (Long menuId : role.getMenuIds()) {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (!list.isEmpty()) {
//            rows = roleMenuMapper.batchRoleMenu(list);
            for (SysRoleMenu sysRoleMenu : list) {
                roleMenuMapper.insert(sysRoleMenu);
            }
        }
        return rows;
    }

    /**
     * 新增角色部门信息(数据权限)
     *
     * @param role 角色对象
     */
    public int insertRoleDept(SysRole role) {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<SysRoleDept> list = new ArrayList<SysRoleDept>();
        for (Long deptId : role.getDeptIds()) {
            SysRoleDept rd = new SysRoleDept();
            rd.setRoleId(role.getRoleId());
            rd.setDeptId(deptId);
            list.add(rd);
        }
        if (!list.isEmpty()) {
            for (SysRoleDept sysRoleDept : list) {
                rows += roleDeptMapper.insert(sysRoleDept);
            }
        }
        return rows;
    }

    /**
     * 通过角色ID删除角色
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteRoleById(Long roleId) {
        // 删除角色与菜单关联
//        roleMenuMapper.deleteRoleMenuByRoleId(roleId);
        LambdaQueryWrapper<SysRoleMenu> dwrapper = new LambdaQueryWrapper<SysRoleMenu>();
        dwrapper.eq(SysRoleMenu::getRoleId, roleId);
        roleMenuMapper.delete(dwrapper);
        // 删除角色与部门关联
//        roleDeptMapper.deleteRoleDeptByRoleId(roleId);
        LambdaQueryWrapper<SysRoleDept> wrapper = new LambdaQueryWrapper<SysRoleDept>();
        wrapper.eq(SysRoleDept::getRoleId, roleId);
        roleDeptMapper.delete(wrapper);
//        return roleMapper.deleteRoleById(roleId);
        SysRole sysRole = new SysRole();
        sysRole.setDelFlag("2");
        sysRole.setUpdateBy(SecurityUtils.getUsername());
        sysRole.setUpdateTime(new Date());
        sysRole.setUpdateTime(DateUtils.getNowDate());
        sysRole.setRoleId(roleId);
        // 执行更新操作并返回是否成功
        return roleMapper.updateById(sysRole);
    }

    /**
     * 批量删除角色信息
     *
     * @param roleIds 需要删除的角色ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteRoleByIds(Long[] roleIds) {
        for (Long roleId : roleIds) {
            checkRoleAllowed(new SysRole(roleId));
            checkRoleDataScope(roleId);
            SysRole role = selectRoleById(roleId);
            if (countUserRoleByRoleId(roleId) > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }
        }
        // 删除角色与菜单关联
//        roleMenuMapper.deleteRoleMenu(roleIds);
        roleMenuMapper.deleteBatchIds(Arrays.asList(roleIds));
        // 删除角色与部门关联
//        roleDeptMapper.deleteRoleDept(roleIds);
        roleDeptMapper.deleteBatchIds(Arrays.asList(roleIds));
//        return roleMapper.deleteRoleByIds(roleIds);
        // 构建批量更新条件
        LambdaUpdateWrapper<SysRole> updateWrapper = new LambdaUpdateWrapper<SysRole>()
                .set(SysRole::getDelFlag, "2")
                .in(SysRole::getRoleId, Arrays.stream(roleIds).collect(Collectors.toList()));
        return roleMapper.update(null, updateWrapper);
    }

    /**
     * 取消授权用户角色
     *
     * @param userRole 用户和角色关联信息
     * @return 结果
     */
    @Override
    public int deleteAuthUser(SysUserRole userRole) {
//        return userRoleMapper.deleteUserRoleInfo(userRole);
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getRoleId, userRole.getRoleId())
                .eq(SysUserRole::getUserId, userRole.getUserId());
        return userRoleMapper.delete(wrapper);
    }

    /**
     * 批量取消授权用户角色
     *
     * @param roleId  角色ID
     * @param userIds 需要取消授权的用户数据ID
     * @return 结果
     */
    @Override
    public int deleteAuthUsers(Long roleId, Long[] userIds) {
//        return userRoleMapper.deleteUserRoleInfos(roleId, userIds);
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getRoleId, roleId)
                .in(SysUserRole::getUserId, Arrays.asList(userIds));
        return userRoleMapper.delete(wrapper);
    }

    /**
     * 批量选择授权用户角色
     *
     * @param roleId  角色ID
     * @param userIds 需要授权的用户数据ID
     * @return 结果
     */
    @Override
    public int insertAuthUsers(Long roleId, Long[] userIds) {
        // 新增用户与角色管理
        List<SysUserRole> list = new ArrayList<SysUserRole>();
        for (Long userId : userIds) {
            SysUserRole ur = new SysUserRole();
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            list.add(ur);
        }
        for (SysUserRole sysUserRole : list) {
            userRoleMapper.insert(sysUserRole);
        }
        return 1;
    }

}
